/***
 * 此service提供课程的增晒查改功能，即课程数据的关系数据库存储功能
 */
import relationalStore from '@ohos.data.relationalStore';
import Constants from "../constants/Constants"
import { ToDo } from '../entity/ToDo';

class ManagerService{

  private rdbStore: relationalStore.RdbStore;
  private dbName : string;

  public initCourseDB(context) {
    const STORE_CONFIG = {
      name: 'courseDB.db', // 数据库文件名
      securityLevel: relationalStore.SecurityLevel.S1 // 数据库安全级别
    };
    const SQL_CREATE_TABLE = `CREATE TABLE IF NOT EXISTS MANAGER(
                              KEY INTEGER PRIMARY KEY AUTOINCREMENT,
                              NAME STRING NOT NULL,
                              COLOR STRING,
                              ISFINISHED INTEGER
                              )`

    relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => {
      if (err) {
        console.error(`创建待办任务表失败！ Code:${err.code}, message:${err.message}`);
        return;
      }
      console.info(`创建待办任务表成功！`);
      // 创建数据表
      store.executeSql(SQL_CREATE_TABLE);
      this.dbName = Constants.MANAGERTABLE_NAME;
      this.rdbStore = store;
    });
  }

  addCourseData(itemData : ToDo):number{
    let id : number = -1;
    const valueBucket = {
      "NAME": itemData.name,
      "COLOR": itemData.color,
      "ISFINISHED":itemData.isFinished,
    };
    let promise = this.rdbStore.insert(this.dbName, valueBucket);
    promise.then((rowId) => {
      console.info(`插入数据成功, rowId = ${rowId}`);
      id = rowId;
    }).catch((err) => {
      console.error(`插入数据失败, code is ${err.code},message is ${err.message}`);
    })
    return id;
  }

  deleteCourseData(id : number):boolean{
    let statu : boolean = false;
    let predicates = new relationalStore.RdbPredicates(this.dbName);
    predicates.equalTo("KEY", id);
    let promise = this.rdbStore.delete(predicates);
    promise.then((rows) => {
      console.info(`删除数据成功，Delete rows: ${rows}`);
      statu = rows > 0;
    }).catch((err) => {
      console.error(`Delete failed, code is ${err.code},message is ${err.message}`);
    })
    return statu;
  }

  deleteAllCourseData():boolean{
    let statu : boolean = false;
    const SQL_DELETE_TABLE = "DELETE FROM " + this.dbName;
    let promise = this.rdbStore.executeSql(SQL_DELETE_TABLE);
    promise.then(() => {
      statu = true;
      console.info(`数据全部删除成功.`);
    }).catch((err) => {
      console.error(`数据全部删除失败, code is ${err.code},message is ${err.message}`);
    })
    return statu;
  }

  updateCourseData(itemData : ToDo):boolean{
    let statu : boolean = false;
    const valueBucket = {
      "NAME": itemData.name,
      "COLOR": itemData.color,
      "ISFINISHED":itemData.isFinished,
    };
    let predicates = new relationalStore.RdbPredicates(this.dbName);
    predicates.equalTo("KEY", itemData.key);
    let promise = this.rdbStore.update(valueBucket, predicates);
    promise.then(async (rows) => {
      console.info(`Updated row count: ${rows}`);
      statu = rows > 0;
    }).catch((err) => {
      console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
    })
    return statu;
  }

  async queryCourseData():Promise<Array<ToDo>>{
    // 正常启动使用
    // let managerList : Array<ToDo> = [];
    // let predicates = new relationalStore.RdbPredicates(this.dbName);
    // let resultSet  = await this.rdbStore.query(predicates,
    //   ["KEY", "NAME", "COLOR","ISFINISHED"]);
    // while (!resultSet.isAtLastRow){
    //   resultSet.goToNextRow();
    //   let key = resultSet.getLong(resultSet.getColumnIndex('KEY'));
    //   let name = resultSet.getString(resultSet.getColumnIndex('NAME'));
    //   let color = resultSet.getString(resultSet.getColumnIndex('COLOR'));
    //   let isFinished = resultSet.getString(resultSet.getColumnIndex('ISFINISHED'));
    //   let itemData:ToDo = new ToDo(key,name,color,isFinished);
    //   managerList.push(itemData);
    // }
    // console.info("数据获取成功:"+JSON.stringify(managerList));

    // 预览器测试专用
    let managerList:Array<ToDo> = Constants.managerList;

    return managerList;
  }

}

let managerService = new ManagerService();
export default managerService as ManagerService;